//
//  SRMyBookListViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/9/5.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRMyBookListViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "FZHomeConstants.h"
#import "SRCommonConstants.h"
#import "FZHomeAlbumCollectionViewCell.h"

#import "FZMCCacheManager.h"
#import "UIAlertView+SRBlocks.h"
#import "SRLearnAlbumViewController.h"
#import "SRGradeListViewController.h"


@interface SRMyBookListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate, FZHomeAlbumCollectionViewCellDelegate>

@property (strong, nonatomic) UICollectionView          *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) NSMutableArray            *items;
@property (assign, nonatomic) NSInteger                 start;

@property (strong, nonatomic) FZHomeCourseModel *addCourseModel;
@property (assign, nonatomic) BOOL isEditing;
@property (strong, nonatomic) NSIndexPath *deleteIndexPath;
@property (strong, nonatomic) UIButton *editButton;

@end

@implementation SRMyBookListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view
    self.title = @"我的教材";
    
    [self setupData];
    [self setupCollectionView];
    [self setupNavigationButton];
    
//    [self startProgressHUD];
    
//    ESWeakSelf;
//    self.loadingView.clickButtonBlock = ^(id sender){
//        ESStrongSelf;
//        [_self queryData];
//    };
    
//    [self showLoadingViewWithCompletedBlock:nil];
//    [self queryData];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self reloadDataFromBooks];

}



#pragma mark - Init UI

- (void)reloadDataFromBooks {
    NSArray *books = [FZMCCacheManager defaultManager].books;
    if ([books count] > 0) {
        [self.items removeAllObjects];
        [self.items addObjectsFromArray:books];
    }
    
    [self.collectionView reloadData];
}

- (void)setupData {
    self.items = [NSMutableArray arrayWithCapacity:0];
    self.start = 0;
    
    FZHomeCourseModel *addModel = [[FZHomeCourseModel alloc] init];
    addModel.title = @"添加";
    addModel.identifier = kHomeAddAlbumID;
    self.addCourseModel = addModel;
    self.isEditing = NO;
    
}

-(void)setupCollectionView
{
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    CGFloat itemSpace = kFZHomeCollectionViewEdgeSpace;
    CGFloat cellWidth = floorf((SCREEN_WIDTH - kFZHomeCollectionViewEdgeSpace * 4) / 3.f) - 1;
    CGFloat cellHeight = cellWidth * cCoverImageRatioHeightToWidth;
    
    flowLayout.itemSize = CGSizeMake(cellWidth, cellHeight);
    flowLayout.minimumLineSpacing = itemSpace;
    flowLayout.minimumInteritemSpacing = itemSpace;
    flowLayout.sectionInset = UIEdgeInsetsMake(kFZHomeCollectionViewEdgeSpace, kFZHomeCollectionViewEdgeSpace, kFZHomeCollectionViewEdgeSpace, kFZHomeCollectionViewEdgeSpace);
    
    self.flowLayout = flowLayout;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    
    [self.collectionView registerNib:[UINib nibWithNibName:kFZHomeAlbumCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kFZHomeAlbumCollectionViewCell];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.alwaysBounceVertical = YES;
    
    [self.view addSubview:self.collectionView];
    
    self.collectionView.backgroundColor = css.color_2;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.view.backgroundColor = css.color_2;
    
        //    ESWeakSelf;
        //
        //    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        //        ESStrongSelf;
        //        _self.start = 0;
        //        [_self queryListData:YES];
        //    }];
        //
        //    [self.collectionView addLegendFooterWithRefreshingBlock:^{
        //        ESStrongSelf;
        //        [_self queryListData:YES];
        //    }];
}

- (void)setupNavigationButton {
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [editButton setTitleColor:css.colorOfGreenButtonNormal forState:UIControlStateNormal];
    [editButton setTitleColor:css.colorOfGreenButtonDisabled forState:UIControlStateDisabled];
    [editButton setTitleColor:css.colorOfGreenButtonHightlighted forState:UIControlStateHighlighted];
        //    [editButton setTitle:@"管理" forState:UIControlStateNormal];
    
    editButton.titleLabel.font = css.fontOfH3;
    [editButton setTitle:@"编辑" forState:UIControlStateNormal];
    
//    [editButton setImage:[UIImage imageNamed:@"study_icon_edit"] forState:UIControlStateNormal];
    
    [editButton addTarget:self action:@selector(onEditButton:) forControlEvents:UIControlEventTouchUpInside];
    editButton.frame = CGRectMake(0, 0, 40.0, 52/2.0);
    
    UIBarButtonItem *editBarItem = [[UIBarButtonItem alloc] initWithCustomView:editButton];
    
    [self setRightBarButtonItem:editBarItem];
    
}

#pragma mark - Event

- (void)onEditButton:(id)sender {
    
    if (self.isEditing) {
            //已经处于多选状态，所以需要取消编辑状态
            //取消选中的cell
//        for (FZHomeCourseModel *model in self.items){
//            model.isSelected = NO;
//        }
        
        self.isEditing = NO;
        [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];

    } else {
            //进入编辑状态
        self.isEditing = YES;
        [self.editButton setTitle:@"取消" forState:UIControlStateNormal];
    }
    
    [self.collectionView reloadData];
    
}


- (void)onAddAlbumButton {
    SRGradeListViewController *vc = [[SRGradeListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showAlbumDetailVC:(FZHomeCourseModel *)item {
    
        //若课本信息已经下载则显示，若没有则提示重新下载
    if ( [[FZMCCacheManager defaultManager] isExistBookFile:item]){
        SRLearnAlbumViewController *vc = [[SRLearnAlbumViewController alloc] init];
        vc.bookID = [NSString stringWithFormat:@"%@", item.identifier];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
            //没有下载文件信息，提示删除再次下载
        [self showHUDErrorMessage:@"还没有下载该教材，请重新添加下载"];
    }
    
}


#pragma mark - Query Data

- (void)queryData{
    self.start = 0;
    [self queryListData:NO];
}


- (void)queryListData:(BOOL)isRefresh {
//    WEAKSELF
//    [FZMyTeachingMaterialService getMyAlbumListStrart:self.start successBlock:^(NSInteger statusCode, NSString *message, id dataObject) {
//        [weakSelf.collectionView.header endRefreshing];
//        [weakSelf.collectionView.footer endRefreshing];
//        if (!isRefresh) {
//            [weakSelf hideLoadingView];
//        }
//        if (statusCode == kFZRequestStatusCodeSuccess && dataObject) {
//            if (!isRefresh || weakSelf.start == 0) {
//                [weakSelf.items removeAllObjects];
//            }
//            NSArray *addItems = dataObject;
//            NSInteger addCount = [addItems count];
//            weakSelf.start += addCount;
//            
//            if (addCount > 0) {
//                [weakSelf.items addObjectsFromArray:addItems];
//            }
//            
//            if (addCount <= 0) {
//                [weakSelf.collectionView.footer setHidden:YES];
//            } else {
//                [weakSelf.collectionView.footer setHidden:NO];
//                [weakSelf.collectionView.footer resetNoMoreData];
//            }
//            
//            if (weakSelf.start == 0 && addCount <= 0) {
//                [weakSelf.loadingView emptyWithTitle];
//            }
//            
//            [weakSelf.collectionView reloadData];
//            
//        } else {
//            [weakSelf showHUDError];
//            if (!isRefresh) {
//                [weakSelf.loadingView failedWithTitle:message];
//            } else if (weakSelf.start == 0) {
//                [weakSelf.loadingView emptyWithTitle];
//            }
//        }
//        
//    } failureBlock:^(id responseObject, NSError *error) {
//        [weakSelf.collectionView.header endRefreshing];
//        [weakSelf.collectionView.footer endRefreshing];
//        [weakSelf showHUDError];
//        if (!isRefresh) {
//            [weakSelf.loadingView failed];
//        }
//    }];
    
}

#pragma mark - UICollectionDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (!self.isEditing) {
        return [self.items count] + 1;
    }
    return [self.items count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FZHomeAlbumCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kFZHomeAlbumCollectionViewCell forIndexPath:indexPath];
    
    if (indexPath.item == [self.items count]) {
            //添加课本按钮
        FZHomeAlbumCollectionViewCell *albumCell = (FZHomeAlbumCollectionViewCell *)cell;
        albumCell.albumMarkHidden = NO;
        albumCell.isAlbum = YES;
        albumCell.indexPath = indexPath;
        albumCell.delegate = nil;
        albumCell.checkButtonHidden = YES;
        albumCell.progressHidden = YES;
        [cell updateCellInfo:self.addCourseModel];
    } else {
        FZHomeCourseModel *model = self.items[indexPath.item];
        FZHomeAlbumCollectionViewCell *albumCell = (FZHomeAlbumCollectionViewCell *)cell;
        albumCell.albumMarkHidden = NO;
        albumCell.isAlbum = YES;
        albumCell.indexPath = indexPath;
        albumCell.delegate = self;
        albumCell.checkButtonHidden = !self.isEditing;
        albumCell.progressHidden = NO;
        
        [cell updateCellInfo:model];
    }

    return cell;
}

#pragma mark - UICollectionDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == [self.items count]) {
            //添加课本按钮
        [self onAddAlbumButton];
    } else {
        FZHomeCourseModel *item = self.items[indexPath.item];
        NSString *bookID = item.identifier;
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:bookID forKey:SRUserCurrentBookID];
        [userDefaults synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:SRUserBookDidChangeNotification object:nil];
        
        
        [self doBack];
        
//            //显示课程学习
//        [self showAlbumDetailVC:item];
    }
    
}

#pragma mark - FZHomeAlbumCollectionViewCellDelegate -

- (void)albumCollectionViewCell:(FZHomeAlbumCollectionViewCell*)cell didSelectItemIndexPath:(NSIndexPath *)indexPath {
    
    self.deleteIndexPath = indexPath;
    NSArray *books = self.items;
    
        WEAKSELF
        if (indexPath.item < [books count]) {
            
            FZHomeCourseModel *item = [books objectAtIndex:indexPath.item];
            NSString *message = [NSString stringWithFormat:@"是否删除 %@", item.title];
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"课程删除"
                                                                message:message
                                                       cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
                
                
                
            }]
                                                       otherButtonItems:[RIButtonItem itemWithLabel:@"删除" action:^{
                [[FZMCCacheManager defaultManager] removeBookAtIndex:weakSelf.deleteIndexPath.item];
                
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [weakSelf.collectionView reloadData];
                    [weakSelf reloadDataFromBooks];
                });
                
            }], nil];
            [alertView show];
            
                //            [[FZMCCacheManager defaultManager] removeBookAtIndex:indexPath.item];
                //            [self.collectionView reloadData];
        }
    
    
    
}

- (void)albumCollectionViewCell:(FZHomeAlbumCollectionViewCell *)cell deleteItemIndexPath:(NSIndexPath *)indexPath {

    NSArray *books = self.items;
    if (indexPath.item < [books count]) {
        [[FZMCCacheManager defaultManager] removeBookAtIndex:indexPath.item];
//        [self.collectionView reloadData];
        [self reloadDataFromBooks];
    }
}


@end
